#include <stdio.h>
#include <signal.h>
int j = 0;
void sig_alarm(int n)
{
	j = 1;
	return;
}
int my_sleep(int nsec)
{
	struct sigaction new, old;
	sigset_t newmask, oldmask, susmask;
	new.sa_handler = sig_alarm;
	new.sa_flags = 0;
	sigemptyset(&new.sa_mask);
	sigaction(SIGALRM, &new, &old);
	//block signal alarm
	sigemptyset(&newmask);
	sigaddset(&newmask, SIGALRM);
	sigprocmask(SIG_BLOCK, &newmask, &oldmask);

	alarm(nsec);

	//unblock sigal alarm
	//pause();
	susmask = oldmask;
	sigdelset(&susmask, SIGALRM);
	sigsuspend(&susmask);
	
	int unsleep = alarm(0);
	sigaction(SIGALRM, &old, NULL);

	//reset
	sigprocmask(SIG_SETMASK, &oldmask, NULL);
	return unsleep;
}
void main(void)
{
	int i = 10;
	while (i--) {
		j = 0;
		my_sleep(1);
		printf("weakup after sleeping 1 sec %d\n", j);
	}
}
